package keyboaUtil.userData;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 2B键盘
 * @version 1.0
 * @create: 2018-04-26 0:29
 * @desc
 **/
public class MyCookie {

    private static String identity;
    private static String password;

    /**
     * 用户账号
     */
    public static final String KEYBOARD_IDENTITY = "KEYBOARD_IDENTITY";
    /**
     * 用户密码
     */
    public static final String KEYBOARD_PASSWORD = "KEYBOARD_PASSWORD";

    public static Map getCookie(HttpServletRequest request){

        Map<String,String> map = new HashMap<>();

        identity = null;
        password = null;
        HttpSession session = request.getSession();
        /**
         * 拿到cookie中的数据
         */
        Cookie[] cookies = request.getCookies();
        for(int i=0; i<cookies.length; i++){
            if(cookies[i].getName().equals(MyCookie.KEYBOARD_IDENTITY) ||
                    cookies[i].getName() == MyCookie.KEYBOARD_IDENTITY){
                identity = cookies[i].getValue();
                System.out.println("COOKIE: "+cookies[i].getName()+"------------>"+cookies[i].getValue());
            }
            if(cookies[i].getName().equals(MyCookie.KEYBOARD_PASSWORD) ||
                    cookies[i].getName() == MyCookie.KEYBOARD_PASSWORD){
                password = cookies[i].getValue();
                System.out.println("COOKIE: "+cookies[i].getName()+"------------>"+cookies[i].getValue());
            }
        }
        map.put(KEYBOARD_IDENTITY,identity);
        map.put(KEYBOARD_PASSWORD,password);

        return map;
    }

    public static void deleteCookie(HttpServletResponse response){
        Cookie cookie1 = new Cookie(MyCookie.KEYBOARD_IDENTITY,null);
        Cookie cookie2 = new Cookie(MyCookie.KEYBOARD_PASSWORD,null);
        cookie1.setMaxAge(0);
        cookie2.setMaxAge(0);
        cookie1.setPath("/");
        cookie2.setPath("/");
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        System.out.println("cookie---->delete");
    }

}
